package pe.edu.upc.e41a.javasoft.daoImpl;

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.springframework.orm.jpa.JpaSystemException;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import pe.edu.upc.e41a.javasoft.dao.AvisoDao;
import pe.edu.upc.e41a.javasoft.domain.Aviso;

@Repository(value = "AvisoDao")
public class AvisoDaoImpl implements AvisoDao {

	// private static final Log log = LogFactory.getLog(AvisoDaoImpl.class);

	private EntityManager em = null;

	@PersistenceContext
	public void setEntityManager(EntityManager em) {
		this.em = em;
	}

	@Transactional(readOnly = true)
	@Override
	public long countAvisoes() {
		return em.createQuery("SELECT COUNT(o) FROM Aviso o", Long.class)
				.getSingleResult();
	}

	@Transactional(readOnly = true)
	@Override
	public List<Aviso> listarTodosAvisos() {
		return em.createQuery("SELECT o FROM Aviso o", Aviso.class)
				.getResultList();
	}

	@Transactional(readOnly = true)
	@Override
	public Aviso buscarAvisoporCodigo(Integer idAviso) {
		if (idAviso == null)
			return null;
		return em.find(Aviso.class, idAviso);
	}

	@Transactional(readOnly = true)
	@Override
	public List<Aviso> buscarAvisoPorFechayPosicion(Date fecha, int posicion) {

		TypedQuery<Aviso> q = em
				.createQuery(
						"SELECT o FROM Aviso o WHERE o.posicion = :posicion"
								+ " AND :fechaInicio BETWEEN o.fechaInicio AND o.fechaFin",
						Aviso.class);

		q.setParameter("posicion", posicion);
		q.setParameter("fechaInicio", fecha);

		return q.getResultList();
	}

	@Transactional(readOnly = true)
	@Override
	public void grabarAviso(Aviso aviso) {
		try {
			em.persist(aviso);
		} catch (JpaSystemException pe) {
			pe.printStackTrace();
		}
	}

	@Transactional(readOnly = true)
	@Override
	public void actualizarAviso(Aviso aviso) {
		em.merge(aviso);
	}

	@Transactional(readOnly = true)
	@Override
	public void eliminarAviso(Aviso aviso) {
		//if (em == null)
		//	this.em = this.em;
		if (em.contains(aviso)) {
			em.remove(aviso);
		} else {
			Aviso attached = this.buscarAvisoporCodigo(aviso.getCodigo());
			em.remove(attached);
		}
	}

}